package com.yu.smsinterceptor;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.yu.smsinterceptor.adapter.MessageListAdapter;
import com.yu.smsinterceptor.mode.Message;
import com.yu.smsinterceptor.service.MessageService;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {

    @ViewInject(R.id.recyclerView)
    private RecyclerView mRecyclerView;
    private MessageListAdapter mAdapter;

    private MessageService mService = new MessageService();
    //拦截的短信集合
    private List<Message> data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new MessageListAdapter(this, data);
        mRecyclerView.setAdapter(mAdapter);
    }

    /**
     *
     * @param v
     */
    @Event(R.id.img_add_phone)
    private void addInterceptPhone(View v) {
        Intent intent = new Intent(this, InterceptPhoneActivity.class);
        startActivity(intent);
    }

    /**
     * 更新 UI
     */
    public void updateUI() {
        new RefreshThread().start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUI();
    }

    //刷新
    private static final int REFRESH = 1;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case REFRESH:
                    //接收到刷新指令后刷新界面
                    data = (List<Message>) msg.obj;
                    mAdapter.refresh(data);
                    break;
            }

        }
    };

    /**
     * 刷新线程
     */
    class RefreshThread extends Thread {

        @Override
        public void run() {
            super.run();
            List<Message> list = mService.list();
            android.os.Message msg = new android.os.Message();
            msg.what = REFRESH;
            msg.obj = list;
            mHandler.sendMessage(msg);
        }
    }

}
